/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

/* $Id: play_wav.c 44 2007-08-08 06:45:33Z kf701.ye $ */

#include "factory.h"

#include <errno.h>
#include <sys/soundcard.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>

bool play_wav(char *dev, char *wav_file, long speed)
{
	int dsp_fd = open(dev, O_WRONLY);
	if ( dsp_fd < 0 )
	{
		return false;
	}

	if(ioctl(dsp_fd,SNDCTL_DSP_SPEED,&speed) == -1)
	{
		close(dsp_fd);
		return false;
	}

	int vfd = open(wav_file, O_RDONLY);
	if ( vfd < 0 )
	{
		close(dsp_fd);
		return false;
	}

	struct stat stat_buf;
	if( 0 != lstat( wav_file, &stat_buf ) )
	{
		close(vfd);
		close(dsp_fd);
		return false;
	}

	char wav_content[stat_buf.st_size] , *ptr ;
	if ( stat_buf.st_size != read(vfd, wav_content, stat_buf.st_size ) )
	{
		close(vfd);
		close(dsp_fd);
		return false;
	}
	close(vfd);

	ptr = wav_content; int find_len = 1000;
	do
	{
		ptr = memchr( ptr, 'd', find_len );
		if ( ptr == NULL )
		{
			close(dsp_fd);
			return false;
		}
		if ( 0 == strncmp(ptr , "data" , 4 ) )
			break ;
		else {
			find_len -= ptr - wav_content ;
			ptr += 1;
		}
	} while ( find_len > 0 );

	if ( find_len <= 0 )
	{
		close(dsp_fd);
		return false;
	}
	else
		ptr += 4;

	uint32_t play_length = 0;
	memcpy( &play_length , ptr ,4 );

	uint8_t tbuf[8];
	bzero(tbuf,8);
	for (  ptr+=4 ; play_length >= 4 ; play_length -= 4 , ptr+=4 )
	{
		memcpy( tbuf, ptr ,4 );
		if ( write(dsp_fd , tbuf, 8) != 8 )
		{
			break;
		}
		bzero(tbuf,8);
	}

	close(dsp_fd);
	return true;
}

